import { deepClone } from '../../utils'
/** 简单柱状图(只有柱子) */
const defaultSimpleBarOption = {
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'none' }
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: { show: false },
    axisLine: { show: false },
    axisLabel: { show: false }
  },
  yAxis: {
    type: 'value',
    axisTick: { show: false },
    axisLine: { show: false },
    axisLabel: { show: false },
    splitLine: { show: false }
  },
  series: [],
  dataset: {
    source: []
  }
}

export function getSimpleBarOption(title = '', source = [], type = 'bar') {
  const option = defaultSimpleBarOption
  option.title.text = title
  option.dataset.source = source
  if (source.length > 0) {
    option.series = source[0].slice(1).map(s => {
      return {
        type: type
      }
    })
  }

  return option
}

/** 仪表盘 */
export const defaultGaugeOption = {
  title: {
    text: ''
  },
  legend: { show: false, orient: 'vertical', right: '5%', top: '15%', icon: 'circle' },
  tooltip: {},
  series: [
    {
      name: '业务指标',
      type: 'gauge',
      detail: { formatter: '{value}' },
      data: []
    }
  ]
}

export function getGaugeOption(title = '', source = [], type = 'gauge') {
  const option = defaultGaugeOption

  if (source.length > 0) {
    option.series[0].data = source.map(value => {
      return {
        name: value[0],
        value: value[1]
      }
    })
  }

  option.title.text = title
  return option
}

/** 雷达图 */
export const defaultRadarOption = {
  title: {
    text: ''
  },
  legend: {
    data: []
  },
  tooltip: {},
  radar: {
    // shape: 'circle',
    name: {
      textStyle: {
        color: '#fff',
        backgroundColor: '#999',
        borderRadius: 3,
        padding: [3, 5]
      }
    },
    indicator: []
  },
  series: [{
    name: '',
    type: 'radar',
    // areaStyle: {normal: {}},
    data: []
  }]
}

export function getRadarOption(title = '', source = [], type = 'radar') {
  const option = defaultRadarOption

  if (source.length > 0) {
    // 雷达图 indicator
    option.radar.indicator = source[0].slice(1).map((value, index) => {
      return {
        name: value,
        max: source[1][index + 1]
      }
    })

    // 雷达图 data
    for (let i = 2; i < source.length; i++) {
      var item = {}
      item.name = source[i][0]
      item.value = source[i].slice(1)
      option.series[0].data.push(item)
    }
  }

  option.title.text = title
  return option
}

/** 甜甜圈 */
export const defaultDoughnutOption = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: ({d}%)'
  },
  legend: {
    show: false,
    orient: 'vertical',
    right: 10
    // data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
  },
  series: [
    {
      name: '',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: true
      }
    }
  ],
  dataset: {
    source: []
  }
}

// export function getDoughnutOption(title = '', source = [], type = 'bar') {
//   const option = defaultDoughnutOption
//   option.title.text = title
//   option.dataset.source = source
//   return option
// }

export function getDoughnutOption(config) {
  const option = defaultDoughnutOption
  option.title.text = config.title
  option.dataset.source = config.dataSource
  return option
}

export const defaultPieOption = {
  title: {
    text: ''
  },
  animationDuration: 1000,
  animationDurationUpdate: 800,
  legend: { show: false, orient: 'vertical', right: '5%', top: '15%', icon: 'circle' },
  tooltip: {},
  series: [
  ],
  dataset: {
    source: []
  }
}

export function getPieOption(config) {
  if (!config.type) {
    throw new Error(config.type + ' config.type不能为空')
  }
  if (!config.dataSource) {
    throw new Error(config.type + ' config.dataSource不能为空')
  }

  const option = defaultPieOption

  if (config.type === 'pie') {
    option.title.text = config.title
    option.dataset.source = config.dataSource
    if (config.dataSource.length > 0) {
      option.series = config.dataSource[0].slice(1).map(s => {
        return {
          type: 'pie'
        }
      })
    }
  } else if (config.type === 'pieNest') {
    option.tooltip = {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    }
    option.legend = {
      show: false,
      orient: 'vertical',
      left: 10
      // data: ['直达', '营销广告', '搜索引擎', '邮件营销', '联盟广告', '视频广告', '百度', '谷歌', '必应', '其他']
    }
    option.series = [
      {
        name: '',
        type: 'pie',
        selectedMode: 'single',
        radius: [0, '30%'],
        label: {
          position: 'inner'
        },
        labelLine: {
          show: false
        },
        data: []
      },
      {
        name: '',
        type: 'pie',
        radius: ['40%', '55%'],
        label: {
          // formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
          formatter: '{b|{b}}\n{c}{per|{d}%}',
          backgroundColor: '#eee',
          borderColor: '#aaa',
          borderWidth: 1,
          borderRadius: 4,
          shadowBlur: 3,
          shadowOffsetX: 2,
          shadowOffsetY: 2,
          shadowColor: '#999',
          padding: [0, 3],
          rich: {
            a: {
              color: '#999',
              lineHeight: 16,
              align: 'center'
            },
            // abg: {
            //     backgroundColor: '#333',
            //     width: '100%',
            //     align: 'right',
            //     height: 22,
            //     borderRadius: [4, 4, 0, 0]
            // },
            hr: {
              borderColor: '#aaa',
              width: '100%',
              borderWidth: 0.5,
              height: 0
            },
            b: {
              fontSize: 12,
              lineHeight: 20
            },
            per: {
              color: '#eee',
              backgroundColor: '#334455',
              padding: [2, 4],
              borderRadius: 2
            }
          }
        },
        data: []
      }
    ]

    const dataSource = deepClone(config.dataSource)

    const data0 = []
    const data1 = []
    option.series[0].name = dataSource[0][0]
    option.series[1].name = dataSource[0][0]

    const sumArr = new Array(dataSource[0].length).fill().map((item, index) => {
      return 0
    })
    for (let i = 0; i < dataSource.length; i++) {
      const item = dataSource[i]
      if (i > 0) {
        for (let j = 0; j < item.length; j++) {
          const item2 = item[j]
          if (j > 0) {
            sumArr[j] += parseFloat(item2)
          }
        }
      }
    }

    for (let i = 0; i < dataSource[0].length; i++) {
      if (i > 0) {
        const _name = dataSource[0][i]
        data0.push({
          name: _name,
          value: Math.floor(sumArr[i] * 100) / 100
          // selected: i === 1
        })
      }

      for (let j = 0; j < dataSource.length; j++) {
        if (j > 0) {
          data1.push({
            value: dataSource[j][i],
            name: dataSource[0][i] + '-' + dataSource[j][0]
          })
        }
      }
    }

    option.series[0].data = data0
    option.series[1].data = data1
  }

  return option
}

function getDefaultBarOption(config) {
  let opt = null
  let legendStatus = false
  if(config.legendStatus){
    legendStatus = true
  }
  if (config.type === 'bar') {
    opt = {
      title: {
        text: ''
      },
      dataZoom: [
        {
          show: false, // 是否显示滑动条，不影响使用
          type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
          startValue: 0, // 从头开始。
          endValue: 5 // 一次性展示多少个。
        },
			],
      color: config.colors,
      animation: !!config.animation,
      animationDuration: 1000,
      animationDurationUpdate: 800,
      tooltip: {
        trigger: 'axis',
        // 折线（区域）图、柱状（条形）图、K线图 : {a}（系列名称），{b}（类目值），{c}（数值）, {d}（无）
        formatter: config.formatter && config.formatter.tooltip ? config.formatter.tooltip : ''
      },
      legend: { show: legendStatus, left: 0, top: 0},
      toolbox: { show: true, feature: { magicType: { show: true, type: ['bar', 'line'] }, restore: { show: true }}},
      grid: { left: '5%', right: '5%', top: '15%', bottom: 0, containLabel: true },
      xAxis: {
        type: 'category',
        axisLabel: {
          formatter: config.formatter && config.formatter.x ? config.formatter.x : '{value}'
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: config.formatter && config.formatter.y ? config.formatter.y : '{value}'
        }
      },
      series: [],
      dataset: {
        source: []
      }
    }
  } else if (config.type === 'line') {
    opt = {
      title: {
        text: ''
      },
      dataZoom: [
        {
          show: false, // 是否显示滑动条，不影响使用
          type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
          startValue: 0, // 从头开始。
          endValue: 5 // 一次性展示多少个。
        },
			],
      animationDuration: 1000,
      animationDurationUpdate: 800,
      tooltip: {
        trigger: 'axis', // axis
        // 折线（区域）图、柱状（条形）图、K线图 : {a}（系列名称），{b}（类目值），{c}（数值）, {d}（无）
        formatter: config.formatter && config.formatter.tooltip ? config.formatter.tooltip : ''
      },
      legend: { show: legendStatus, left: 0, top: 0 },
      toolbox: { show: true, feature: { magicType: { show: true, type: ['bar', 'line'] }, restore: { show: true }}},
      grid: { left: '5%', right: '5%', top: '15%', bottom: 0, containLabel: true },
      xAxis: {
        type: 'category',
        axisLabel: {
          formatter: config.formatter && config.formatter.x ? config.formatter.x : '{value}'
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: config.formatter && config.formatter.y ? config.formatter.y : '{value}'
        }
      },
      series: [],
      dataset: {
        source: []
      }
    }
    if (config.shadow === true) {
      opt = Object.assign(opt, {
        lineStyle: {
          width: 3,
          shadowColor: 'rgba(0,0,0,0.4)',
          shadowBlur: 10,
          shadowOffsetY: 10
        }
      })
    }
  } else if (config.type === 'bar3D') {
    opt = {
      title: {
        text: ''
      },
      animationDuration: 1000,
      animationDurationUpdate: 800,
      tooltip: {
        trigger: 'item',
        formatter: null
      },
      visualMap: {
        max: 100,
        inRange: {
          color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
        },
        show: false
      },
      xAxis3D: {
        type: 'category',
        data: null
      },
      yAxis3D: {
        type: 'category',
        data: null
      },
      zAxis3D: {
        type: 'value'
      },
      grid3D: {
        boxWidth: 160,
        boxDepth: 80,
        viewControl: {
          alpha: 30,
          beta: 15
        }
      },
      series: [{
        type: 'bar3D',
        data: null,
        itemStyle: {
          opacity: 0.7
        },
        label: {
          show: false,
          textStyle: {
            fontSize: 16,
            borderWidth: 1
          }
        },
        emphasis: {
          label: {
            show: false,
            textStyle: {
              fontSize: 20
              // color: '#900'
            }
            // formatter: '{a}==={b}==={c}'
          }
          /* itemStyle: {
            color: '#900'
          } */
        }
      }]
    }
    if (config.shadow === true) {
      opt = Object.assign(opt, {
        lineStyle: {
          width: 3,
          shadowColor: 'rgba(0,0,0,0.4)',
          shadowBlur: 10,
          shadowOffsetY: 10
        }
      })
    }
  }

  if (config.backgroundColor) {
    opt.backgroundColor = config.backgroundColor
  }

  // x轴文字换行显示
  if(config.isXShowState) {
    opt.xAxis.axisLabel = {
      show: true,
      interval: 0,
      formatter: function(params) {
        var newParamsName = "";
        var paramsNameNumber = params.length;
        var provideNumber = 3; //一行显示几个字
        var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
        if (paramsNameNumber > provideNumber) {
          for (var p = 0; p < rowNumber; p++) {
            var tempStr = "";
            var start = p * provideNumber;
            var end = start + provideNumber;
            if (p == rowNumber - 1) {
              tempStr = params.substring(start, paramsNameNumber);
            } else {
              tempStr = params.substring(start, end) + "\n";
            }
            newParamsName += tempStr;
          }
        } else {
          newParamsName = params;
        }
        return newParamsName;
      }
    }
  }

  return opt
}

export function getBarOption(config) {
  if (!config.type) {
    throw new Error(config.type + ' config.type不能为空')
  }
  if (!config.dataSource) {
    throw new Error(config.type + ' config.dataSource不能为空')
  }
  const option = getDefaultBarOption(config)
  option.title.text = config.title
  option.dataset.source = config.dataSource
  if (config.dataSource.length > 0) {
    if(config.topValueStatus) {
      option.series = config.dataSource[0].slice(1).map(s => {
        return {
          type: config.type,
          name: s,
          smooth: config.smooth === true,
          // 测试柱状图显示数据
          itemStyle: {
            barBorderRadius: 5,
            normal: {
              label: {
                show: true,
                position: 'top',
                textStyle: {
                  color: '#466ab1',
                  fontSize: 12
                }
                // formatter(params) {
                //   const data = params.data
                //   const seriesIndex = params.seriesIndex
                //   if(data && undefined !== seriesIndex && (Number(data[1]) + Number(data[2]) + Number(data[3])) !== 0) {
                //     if(seriesIndex === 0){
                //       const percent = Number(data[1]) / (Number(data[1]) + Number(data[2]) + Number(data[3]))
                //       const text = Math.round(percent*100) + '%'
                //       return text
                //     }
                //     if(seriesIndex === 1){
                //       const percent = Number(data[2]) / (Number(data[1]) + Number(data[2]) + Number(data[3]))
                //       const text = Math.round(percent*100) + '%'
                //       return text
                //     }
                //     if(seriesIndex === 2){
                //       if(data[3] !== 0){
                //         const percent = Number(data[3]) / (Number(data[1]) + Number(data[2]) + Number(data[3]))
                //         const text = Math.round(percent*100) + '%'
                //         return text
                //       }
                //     }
                //   }else {
                //     return null
                //   }
                // }
              }
            }
          }
        }
      })
    } else {
      option.series = config.dataSource[0].slice(1).map(s => {
        return {
          type: config.type,
          name: s,
          smooth: config.smooth === true,
        }
      })
    }
  }
  return option
}

export function getBar3DOption(config, colorArr) {
  if (!config.type) {
    throw new Error(config.type + ' config.type不能为空')
  }
  if (!config.dataSource) {
    throw new Error(config.type + ' config.dataSource不能为空')
  }
  const option = getDefaultBarOption(config)
  option.title.text = config.title
  option.visualMap.inRange.color = colorArr

  // data handler start
  const dataSource = deepClone(config.dataSource)
  // option.dataset.dimensions = dataSource[0];
  // option.dataset.source = dataSource.splice(1);
  const xAxis3DData = []
  let yAxis3DData = []
  const mainData = []
  let maxv = 0
  for (let i = 0; i < dataSource.length; i++) {
    const item = dataSource[i]
    if (i === 0) {
      yAxis3DData = item.splice(1)
    }
    if (i > 0) {
      xAxis3DData.push(item[0])
      for (let j = 0; j < item.length; j++) {
        const item2 = item[j]
        if (item2 > maxv) {
          maxv = item2
        }
        if (j > 0) {
          mainData.push([i - 1, j - 1, item2])
        }
      }
    }
  }
  option.visualMap.max = maxv
  option.xAxis3D.data = xAxis3DData
  option.yAxis3D.data = yAxis3DData
  option.tooltip.formatter = (params, ticket, callback) => {
    let ret = ''
    ret = ret.concat(xAxis3DData[params.value[0]])
      .concat('-')
      .concat(yAxis3DData[params.value[1]])
      .concat('<br>')
      .concat(params.marker)
      .concat(' ')
      .concat(params.value[2])
    return ret
  }
  option.series[0].data = mainData
  /* option.series[0].data.emphasis.label = {};
  option.series[0].data.emphasis.label.show = true;
  option.series[0].data.emphasis.label.formatter = '{a}: {b}: {c}'; */

  // data handler end

  return option
}
